﻿using System;
using WiMo.Games.Drawables;
using System.Drawing;

namespace WiMo.Games.GDIDisplay.Drawables
{
    public class Text : SpriteTextBase
    {
        private Bitmap _bitmap = null;

        public Text() 
        {

        }

        public override void Render(IDisplay display)
        {
            display.Render(this);
        }

        public override void Dispose()
        {
            var font = Font.FontInformation as IDisposable;
            if (font != null)
                font.Dispose();

            Font.FontInformation = null;
        }

        private Point GetOrigin(Origin origin, PointF original, Size size)
        {
            var point = new Point();

            if (origin == Origin.TopLeft)
                point = new Point(Convert.ToInt32(original.X), Convert.ToInt32(original.Y));
            else
                point = new Point(Convert.ToInt32(original.X - size.Width / 2), Convert.ToInt32(original.Y - size.Height / 2));

            return point;

            //            return new Point(Convert.ToInt32(point.X * ScaleFactor.X), Convert.ToInt32(point.Y * ScaleFactor.Y));
        }

        public void Render(Graphics graphics)
        {
            if (_bitmap == null)
            {
                if (Font.FontInformation == null)
                {
                    var fontStyle = FontStyle.Regular;
                    if (Font.Bold) fontStyle |= FontStyle.Bold;
                    if (Font.Italics) fontStyle |= FontStyle.Italic;
                    if (Font.Underline) fontStyle |= FontStyle.Underline;
                    if (Font.StrikeThrough) fontStyle |= FontStyle.Strikeout;

                    Font.FontInformation = new Font(Font.Name, Font.Size, fontStyle);
                }

                if (_bitmap == null)
                {
                    var size = graphics.MeasureString(Text, Font.FontInformation as Font);
                    _bitmap = new Bitmap(Convert.ToInt32(size.Width), Convert.ToInt32(size.Height));
                    var bmGraphics = Graphics.FromImage(_bitmap);

                    var sb = new SolidBrush(ForeColor.ToDrawingColor());

                    bmGraphics.DrawString(Text, Font.FontInformation as Font, sb, 0, 0);
                    sb.Dispose();
                    bmGraphics.Dispose();                
                }

                var point = GetOrigin(Origin, Position, new Size(_bitmap.Size.Width, _bitmap.Size.Height));
                graphics.DrawImage(_bitmap, point.X, point.Y);
                
            }
        }


        public override bool CheckForCollision(ISprite sprite)
        {
            return false;
        }

    }
}
